﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LumenWorks.Framework.IO.Csv;
using System.IO; 
using LumenWorks.Framework.Tests.Unit.IO.Csv;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Adex; 
using System.Transactions;
using System.Drawing;
using MediaMonitor.Common;

namespace MediaMonitor.Admin
{
    public partial class RF_Upload_Planning : Adex.BasePage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        private void ManagePost()
        {
        }

        protected void btnUpload_Click(Object sender, EventArgs e)
        {

            string errMsg1, errMsg2, errMsg3, errMsg4, errMsg5, errMsg6, errMsg7;
            errMsg1 = errMsg2 = errMsg3 = errMsg4 = errMsg5 = errMsg6 = errMsg7 = "";


            if (flRF1.PostedFile.FileName.Length > 0)
            {
                lblInfo1.ForeColor = UploadRF(flRF1, out errMsg1) == true ? Color.Blue : Color.Red;
                lblInfo1.Text = errMsg1;
            }
            else
                lblInfo1.Text = "No file selected to upload";


            if (flRF2.PostedFile.FileName.Length > 0)
            {
                lblInfo2.ForeColor = UploadRF(flRF2, out errMsg2) == true ? Color.Blue : Color.Red;
                lblInfo2.Text = errMsg2;
            }
            else
                lblInfo2.Text = "No file selected to upload";

            if (flRF3.PostedFile.FileName.Length > 0)
            {
                lblInfo3.ForeColor = UploadRF(flRF3, out errMsg3) == true ? Color.Blue : Color.Red;
                lblInfo3.Text = errMsg3;
            }
            else
                lblInfo3.Text = "No file selected to upload";

            if (flRF4.PostedFile.FileName.Length > 0)
            {
                lblInfo4.ForeColor = UploadRF(flRF4, out errMsg4) == true ? Color.Blue : Color.Red;
                lblInfo4.Text = errMsg4;
            }
            else
                lblInfo4.Text = "No file selected to upload";

            if (flRF5.PostedFile.FileName.Length > 0)
            {
                lblInfo5.ForeColor = UploadRF(flRF5, out errMsg5) == true ? Color.Blue : Color.Red;
                lblInfo5.Text = errMsg5;
            }
            else
                lblInfo5.Text = "No file selected to upload";

            if (flRF6.PostedFile.FileName.Length > 0)
            {
                lblInfo6.ForeColor = UploadRF(flRF6, out errMsg6) == true ? Color.Blue : Color.Red;
                lblInfo6.Text = errMsg6;
            }
            else
                lblInfo6.Text = "No file selected to upload";

            if (flRF7.PostedFile.FileName.Length > 0)
            {
                lblInfo7.ForeColor = UploadRF(flRF7, out errMsg7) == true ? Color.Blue : Color.Red;
                lblInfo7.Text = errMsg7;
            }
            else
                lblInfo7.Text = "No file selected to upload";


            pnlInfo1.Visible = pnlInfo2.Visible = pnlInfo3.Visible = pnlInfo4.Visible = pnlInfo5.Visible = pnlInfo6.Visible = pnlInfo7.Visible = true;

            pnlUpload.Visible = false;


        }

        private bool UploadRF(FileUpload flRF, out string errMsg)
        {


            byte countryID = AppUser.GetCountry();

            StreamReader readFile = new StreamReader(flRF.PostedFile.InputStream);
          
            //CsvReader csv = new CsvReader(new StringReader(readFile.ReadToEnd()), false, ',', '"', '\\', '☺', ValueTrimmingOptions.All); // for comments char = 122
            CsvReader csv = new CsvReader(new StringReader(readFile.ReadToEnd()), false, ',', '?', '\\', '☺', ValueTrimmingOptions.All); // for comments char = 122
            DataTable dt = GetRFDataTable();
            if (csv.FieldCount != dt.Columns.Count - 1)
            {
                errMsg = "<h2>Upload Failed!!!</h2>Not a valid RF file. Field length is different";
                return false;
            }


            int currentRow = 0;
            int currentCol = 0;

            try
            {
                //fill data from RF file
                while (csv.ReadNextRecord())
                {
                    currentRow += 1;

                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < dt.Columns.Count - 1; i++)
                    {
                        currentCol = i + 1;

                        switch (dt.Columns[i + 1].DataType.Name)
                        {
                            case "DateTime":
                                dr[i + 1] = Utility.IsNullDate(Utility.GetDateFromNumber(csv[i].ToString()));
                                break;
                            case "Int32":
                                dr[i + 1] = Utility.IsNullInt(csv[i]);
                                break;
                            case "String":
                                dr[i + 1] = Utility.IsNullStr(csv[i]);
                                break;
                            case "Boolean":
                                dr[i + 1] = Utility.IsNullBool(csv[i]);
                                break;
                            case "Decimal":
                                dr[i + 1] = Utility.IsNullDec(csv[i]);
                                break;
                            case "Double":
                                dr[i + 1] = Utility.IsNullDec(csv[i]);
                                break;
                        }//end swtich


                    }
                    dt.Rows.Add(dr);
                }

            }
            catch (Exception ex1)
            {

                errMsg = "<h2>Upload Failed!!!</h2>Failed to shift data from CSV to DB. CSV Row: " + currentRow + ", Col: " + currentCol + "." + ex1.Message;
                return false;
            }


            TransactionOptions options = new TransactionOptions();
            options.Timeout = new TimeSpan(0, 2, 0);
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Suppress, options))
            {
                using (SubSonic.SharedDbConnectionScope conn = new SubSonic.SharedDbConnectionScope(System.Configuration.ConfigurationManager.ConnectionStrings["DBAdex"].ToString()))
                {

                    //transaction activities.
                    try
                    {
                        //delete all the Planning Log of same RFDate
                        try
                        {
                          
                            RfController.DeleteAllPlanning();
                        }
                        catch
                        {
                            ts.Dispose();
                            conn.Dispose();

                            errMsg = "<h2>Upload Failed!!!</h2>Failed to Delete previous Planning records of same date.";
                            return false;
                        }


                        foreach (DataRow dr in dt.Rows)
                        {
                              #region  PlanningLog
                              Adex.PlanningLog odLog = new PlanningLog();
                              odLog.MediaCode =Utility.IsNullInt(dr["MediaCode"]);
                              odLog.Carriers = dr["Carriers"].ToString();
                              odLog.Billboardstype = dr["Billboardstype"].ToString();
                              odLog.DateAdded = DateTime.Now;
                              odLog.DateModified = DateTime.Now;
                              odLog.Save();
                             #endregion

                        } //end loop dt

                        ts.Complete();
                    }//end try

                    catch (Exception ex2)
                    {
                        ts.Dispose();

                        conn.Dispose();

                        try
                        {
                            RfController.DeleteAllPlanning();
                        }
                        catch { }

                        errMsg = "<h2>System fails to upload data process</h2>No data uploaded, Please try again.<br>" + ex2.Message;
                        return false;

                    }

                }//end using SharedDBConnection
            }//end using TransactionScope

            errMsg = "<h2>Data Uploaded Successfully</h2>All data from RF file successfully uploaded";
            return true;

        }

        private System.Data.DataTable GetRFDataTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", System.Type.GetType("System.Int32"));
            dt.Columns.Add("MediaCode", System.Type.GetType("System.Int32")); // Avenue is MediaCode
            dt.Columns.Add("Carriers", System.Type.GetType("System.String"));
            dt.Columns.Add("Billboardstype", System.Type.GetType("System.String"));
            return dt;

        }


    }
}